package com.jky.filesystem.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;

public class FileUtils {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, "测试 FileUtils");

    private static final int CACHE_SIZE = 256 * 1024;

    /**
     * 根据uri将文件复制到指定目录
     * @param originUri 源文件uri
     * @param targetDir 目标目录
     * @param context context
     * @return 成功true，失败false
     */
    public static boolean CopyFileToDirByUri(Uri originUri, String targetDir, Context context) {
        try {
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            ResultSet resultSet = null;
            //API 6可以直接通过DataAbilityHelper来查询文件名
            try {
                resultSet = helper.query(originUri, new String[]{
                        AVStorage.AVBaseColumns.DISPLAY_NAME,
                }, null);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            String fileName = "";
            if (resultSet != null && resultSet.goToNextRow()) {
                fileName = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DISPLAY_NAME));;
            }
            HiLog.info(LABEL_LOG,"选择的文件名：" + fileName);
            if(fileName.isEmpty()) throw new FileNotFoundException("文件名为空");
            File disFile = new File(targetDir, fileName);
            FileDescriptor fd = null;
            try {
                fd = helper.openFile(originUri, "r");
            } catch (DataAbilityRemoteException e) {
                HiLog.error(LABEL_LOG, "读取文件失败：" + e.getMessage());
                e.printStackTrace();
            }
            FileInputStream in = new FileInputStream(fd);
            FileOutputStream out = new FileOutputStream(disFile);
            boolean copySuccess = copyFile(in,out);
            if(copySuccess){
                HiLog.info(LABEL_LOG, "复制成功，路径为：" + disFile.getPath());
                return true;
            }
            else {
                return false;
            }
        } catch (FileNotFoundException e) {
            HiLog.error(LABEL_LOG, "创建文件流失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 根据file类型复制文件到指定目录
     * @param originFile 源文件file
     * @param targetDir 目标目录
     * @return 成功true，失败false
     */
    public static boolean CopyFileToDirByFile(File originFile, String targetDir) {
        try {
            File disFile = new File(targetDir, FileUtils.TimeAndRandomStr(originFile.getName()));
            FileInputStream in = new FileInputStream(originFile);
            FileOutputStream out = new FileOutputStream(disFile);
            boolean copySuccess = copyFile(in,out);
            if(copySuccess){
                HiLog.info(LABEL_LOG, "复制成功，路径为：" + disFile.getPath());
                return true;
            }
            else {
                return false;
            }
        } catch (FileNotFoundException e) {
            HiLog.info(LABEL_LOG,"创建文件流失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 复制文件
     * @param in 输入流
     * @param out 输出流
     * @return 成功true，失败false
     */
    private static boolean copyFile(FileInputStream in,FileOutputStream out) {
        try {
            byte[] buffer = new byte[CACHE_SIZE];
            int len;
            HiLog.info(LABEL_LOG,"文件长度：" + buffer.length);
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            HiLog.error(LABEL_LOG, "复制失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 为文件添加时间以及随机数
     * @param fileName 文件名
     * @return 处理后的文件名
     */
    public static String TimeAndRandomStr(String fileName) {
        return TimeAndRandomStr(fileName,100000,999999);
    }

    /**
     * 为文件添加时间以及随机数
     * @param getFileName 文件名
     * @param start 随机数的起始值
     * @param end 随机数的结束值
     * @return 处理后的文件名
     */
    public static String TimeAndRandomStr(String getFileName, Integer start, Integer end) {
        HiLog.info(LABEL_LOG,"原始文件名为：" + getFileName);
        String fileName = getFileName.substring(0,getFileName.lastIndexOf("."));
        String suffix = getFileName.substring(getFileName.lastIndexOf("."));
        //获取当前时间戳
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        int randStr = new Random().nextInt(end-start) + start;
        return fileName + "-" + str + "-" + randStr + suffix;
    }

    /**
     * 将图片转换成base64格式
     * @param path 路径
     * @return 转换后的base64
     */
    private String ImgToBase64(String path) {
        byte[] data = null;
        FileInputStream input;
        try {
            input = new FileInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        }
        catch (IOException ex1) {
            ex1.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
//        String afterEn = encoder.encodeToString(data);
//        HiLog.info(LABEL_LOG, "转换base64后");
//        HiLog.info(LABEL_LOG, afterEn);
        return encoder.encodeToString(data);
    }
}
